﻿$G.pay.ajax = {
	xhrErrorCode: -65535,

	toJSONData: function (data) {
		var d = { token: JSON.stringify(data) };
		return JSON.stringify(d);
	},

	initialize: function(ajaxStartCallback, ajaxStopCallback) {
		$(document).bind("ajaxStart", ajaxStartCallback).bind("ajaxStop", ajaxStopCallback);
	},

	call: function (method, data, s, e) {

		$.ajax({
			type: "POST",
			url: "/Ajax/WebMethods.asmx/" + method,
			data: this.toJSONData(data),
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			async: true,
			success: function (msg) { $G.pay.ajax.ajaxSuccess(msg, s, e); },
			error: function (xhr, status, error) { $G.pay.ajax.ajaxError(xhr, status, error, e); },
		});
	},

	ajaxSuccess: function (msg, s, e) {
		if (msg.d.ErrorCode != '0') {
			if (typeof e !== "undefined") e({ success: false, errorCode: msg.d.ErrorCode, errorMessage: msg.d.ErrorMessage });
		} else if (typeof s !== "undefined") s(msg);
	},

	ajaxError: function(xhr, status, error, e) {
		if (typeof e !== undefined) {
			var err;
			try {
				err = JSON.parse(xhr.responseText);
			}
			catch (exc)
			{
				err = { Message: xhr.responseText };
			}
			e({ success: false, errorCode: this.xhrErrorCode, errorMessage: err.Message });
		}
	},

	initPayment: function (data, successCallback, errorCallback) { this.call("InitPayment", data, successCallback, errorCallback); },
	pay: function (data, successCallback, errorCallback) { this.call("Pay", data, successCallback, errorCallback); },
	vendorLogin: function (data, successCallback, errorCallback) { this.call("GetVendorLogin", data, successCallback, errorCallback); }
}